#include "playlist.h"
#include <QUrl>
#include <QFile>


PlayList::PlayList(QTableWidget *tb, QObject *parent):
   QMediaPlaylist(parent), tb(tb)
{

}

void PlayList::append(Song song)
{
    songList.append(song);
    addMedia(QUrl(song.url));
    songList.wirteToTable(tb);
}

void PlayList::appendAndPlay(Song song)
{
    append(song);
    this->setCurrentIndex(songList.size() - 1);
    songList.wirteToTable(tb);
    emit wantPlay();
}

void PlayList::appendSongList(const SongList &list)
{
    for (int i = 0; i < list.size(); i++) {
        append(list[i]);
    }
    songList.wirteToTable(tb);

}

void PlayList::deleteByIndex(int n)
{
    this->removeMedia(n);
    songList.removeAt(n);
    songList.wirteToTable(tb);
}

void PlayList::clearList()
{
    this->clear();
    songList.clear();
    tb->clear();
    tb->setHorizontalHeaderLabels({"歌名","歌手"});

}

void PlayList::loadList(const SongList &list)
{
    clearList();
    appendSongList(list);
}

void PlayList::saveInFile(QString path)
{
    QFile file(path);
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    out << (QList<Song>)songList;
    file.close();
}

Song &PlayList::getSongByIndex(int n)
{
    static Song err("", "", QUrl(), -1);
    if (n < 0 || n >= songList.size())
        return err;
    return songList[n];
}

Song &PlayList::getCurrentSong()
{
    static Song err("", "", QUrl(), -1);
    if (currentIndex() >= 0) {
        return songList[currentIndex()];
    } else {
        return err;
    }

}

Song &PlayList::getSongById(unsigned int id) {
    static Song err("", "", QUrl(), -1);
    for (int i = 0; i < songList.size(); i++) {
        if (songList[i].id == id)
            return songList[i];
    }
    return err;
}
